<?php
// 初始化结果变量
$result = '';

// 天干数组
$tiangan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
// 地支数组
$dizhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];

// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $ganzhi = $_POST['ganzhi'];
    $gan = mb_substr($ganzhi, 0, 1, 'UTF-8');
    $zhi = mb_substr($ganzhi, 1, 1, 'UTF-8');

    $ganIndex = array_search($gan, $tiangan);
    $zhiIndex = array_search($zhi, $dizhi);

    if ($ganIndex!== false && $zhiIndex!== false) {
        // 已知 1984 年为甲子年
        $baseYear = 1984;
        $baseGanIndex = 0;
        $baseZhiIndex = 0;

        $diffGan = ($ganIndex - $baseGanIndex + 10) % 10;
        $diffZhi = ($zhiIndex - $baseZhiIndex + 12) % 12;

        $commonMultiple = 60; // 天干地支一个循环为 60 年
        $yearDiff = ($diffZhi - $diffGan + $commonMultiple) % $commonMultiple;

        $approximateYear = $baseYear + $yearDiff;

        // 考虑可能的其他循环
        $currentYear = date('Y');
        if ($approximateYear > $currentYear) {
            $approximateYear -= $commonMultiple;
        }

        $result = "干支 “{$ganzhi}” 对应的较近公历年份是 {$approximateYear} 年。";
    } else {
        $result = "输入的干支信息有误，请检查后重新输入。";
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>干支算年份游戏</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <h1>干支算年份游戏</h1>
    <form method="post">
        <label for="ganzhi">请输入干支纪年（如：甲子）：</label>
        <input type="text" id="ganzhi" name="ganzhi" required>
        <input type="submit" value="计算年份">
    </form>
    <?php if ($result): ?>
        <div id="result">
            <p><?php echo $result; ?></p>
        </div>
    <?php endif; ?>
</body>

</html>